package c.main.controller;

import c.main.core.*;
import c.main.domain.LoginUser;
import c.main.service.LoginService;
import c.main.util.RequestMethod;
import c.main.util.StringUtils;
import c.main.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Author: chengwei
 * Date:   2016/1/14
 * Time:   17:33
 */
@WebServlet(urlPatterns = "/login.action")
public class LoginController extends BaseController{
    
    @WcsResource
    private LoginService service; 

    @Override
    public void doDefaultGet(HttpView view) throws ServletException, IOException {
        HttpSession session = view.getSession();
        if (session != null) {
            session.removeAttribute(IAuthorization.SESSION_KEY);
        }
        view.forwardJsp("sys/login");
    }
    
    @WebRequest(act = "admin_login")
    public void adminLogin(HttpView view) throws ServletException, IOException {
        HttpSession session = view.getSession();
        if (session != null) {
            session.removeAttribute(IAuthorization.SESSION_KEY);
        }
        view.forwardJsp("sys/login");
    }

    @WebRequest(act = "do_login",method = RequestMethod.ANY)
    public void doLogin(HttpView view) throws ServletException, IOException {
        HttpSession session = view.getSession();
        if(session != null) {
            String check_code = (String)session.getAttribute(WebUtils.RAND_CHECK_CODE);
            if (StringUtils.isNotEmpty(check_code) && StringUtils.isNotEmpty(view.getParameter("check_code")) 
                    //将session中 和 用户输入的验证码 转换为大写 比较是否相同
                    && check_code.toUpperCase().equals(view.getParameter("check_code").toUpperCase())){
                //验证用户输入的用户名密码是否正确
                LoginUser user = service.getLoginUser(view.getParameter("username"),view.getParameter("password"));
                if (user != null) {
                    session.setAttribute(IAuthorization.SESSION_KEY,user);
                    view.sendRedirect("/user/home.action");
                    return;
                }
            }
        }
        
        view.forwardJsp("sys/login");
    }

    @WebRequest(act = "do_admin_login")
    public void doLoginAdmin(HttpView view) throws ServletException, IOException {
        view.getSession().removeAttribute(IAuthorization.SESSION_KEY);
    }

    
}
